# coding=utf-8
# 全世界最帅的帅哥
import random
import time
from lxml import etree
from ysgg1_club_wx.constant.wx_expire_time import MESSAGE_CODE_EXPIRE_TIME
from ysgg1_club_comment.redis_client import redis_client
from ysgg1_club_wx.config.wx_config import WxConfig
from ysgg1_club_auth.constant.redis_prefix import RedisPrefix


def send_xml(xml_dict):
    root = etree.Element("xml")

    # 创建子元素并添加到根元素中
    to_user = etree.SubElement(root, 'ToUserName')
    to_user.text = etree.CDATA(xml_dict['ToUserName'])

    from_user = etree.SubElement(root, 'FromUserName')
    from_user.text = etree.CDATA(xml_dict['FromUserName'])

    create_time = etree.SubElement(root, 'CreateTime')
    create_time.text = str(time.time())

    msg_type = etree.SubElement(root, 'MsgType')
    # 假设我们要将 MsgType 的值从 'event' 改为 'text'，如目标 XML 所示
    msg_type.text = etree.CDATA(xml_dict['MsgType'])  # 或者使用 data['MsgType'] 根据实际情况

    content = etree.SubElement(root, 'Content')
    content.text = etree.CDATA(xml_dict['Content'])

    # 将 XML 树转换为字符串
    xml_str = etree.tostring(root, encoding='utf-8').decode('utf-8')

    return xml_str


def parse_xml(text):
    xml_data = text.decode("utf-8")
    xml_tree = etree.fromstring(xml_data)

    xml_dict = {}
    for elem in xml_tree.iter():
        xml_dict[elem.tag] = elem.text

    return xml_dict


def handle_msg(xml_dict):
    msg_type = xml_dict['MsgType']
    if msg_type == 'event':
        if xml_dict["Event"] == "subscribe":
            return subscribe_event(xml_dict)
    elif msg_type == "text":
        if xml_dict["Content"] == "验证码":
            return send_code(xml_dict)
    return


def send_code(xml_dict):

    xml_dict["ToUserName"] = xml_dict["FromUserName"]
    xml_dict["FromUserName"] = WxConfig.wx_account
    xml_dict.pop("CreateTime")
    xml_dict["MsgType"] = "text"
    code = str(random.randint(1000, 9999))
    # redis存入验证码和用户的openid  code: openid
    while redis_client.get(code):
        code = str(random.randint(1000, 9999))
    login_key = RedisPrefix.LOGIN_PREFIX + code
    redis_client.setex(login_key, MESSAGE_CODE_EXPIRE_TIME, xml_dict["ToUserName"])

    xml_dict["Content"] = f"您当前的验证码为{code}, 五分钟内有效"
    return send_xml(xml_dict)


def subscribe_event(xml_dict):
    xml_dict["ToUserName"] = xml_dict["FromUserName"]
    xml_dict["FromUserName"] = WxConfig.wx_account
    xml_dict.pop("CreateTime")
    xml_dict["MsgType"] = "text"
    xml_dict["Content"] = "谢谢你的关注"
    return send_xml(xml_dict)
